package middle_ware

import (
	"crypto/rand"
	"encoding/base64"
	"encoding/hex"
	"go-base/src/logs"
	"regexp"
)

var (
	RegCheck         = regexp.MustCompile(`^[0-9a-zA-Z]{6,20}$`)
	RegNickNameCheck = regexp.MustCompile(`^[0-9a-zA-Z]{1,20}$`)
)

// 后台用户的密码的`盐`的生成
func Salt() (string, error) {
	b := make([]byte, 32) // 跟密码长度一样,这里出来是64个字符
	_, err := rand.Read(b)
	if err != nil {
		logs.Error.Printf("用户生成盐报错, %s", err)
		return "", err
	}
	return hex.EncodeToString(b), nil
}

// 是否是有效的密码
func IsValidPassword(s string) (b bool, err error) {
	p, err := decPass(s)
	if err != nil {
		return
	}
	logs.Info.Printf("密码 %s decode成功: %s", s, p)
	return RegCheck.Match([]byte(p)), nil
}

// 解密密码
func decPass(s string) (result string, err error) {
	var temp []byte
	if temp, err = base64.RawStdEncoding.DecodeString(s); err != nil {
		logs.Error.Printf("%s 进行base64 decode出错: %s", s, err)
		return
	}
	result = string(temp)
	return
}
